<?php
require_once 'db/db.php';
require_once 'util/perm.php';

// int -> int
function postCount($threadNum) {
  if( !hasPerm('view.post.count') ) 
    return -1;

  try {
    $db = openDbConn();
    // XXX does this work? I don't member
    $res = $db->query("SELECT COUNT(rank) AS pcount FROM post WHERE tid = $threadNum;")->fetch(); 
    $cnt = $res['pcount'];
    $res = NULL;
    return $cnt;
  } catch ( PDOException $e ) {
    print "ERROR: " . $e->getMessage() . "<br />";
    die();
  }
}

// int -> int -> obj?
function getPosts($threadNum, $start, $inc) {
  if( !hasPerm('view.post') ) 
    return -1;

  try {
    $db = openDbConn();
    $posts = $db->query("SELECT post.title, post.datum, post.rank, post.date, post.tid, user.name AS uname, user.id AS uid, thread.fid AS fid, post.smurfKey 
                         FROM post
                           LEFT JOIN user, thread
                             ON post.uid = user.id
                             AND thread.id = post.tid
                           WHERE post.tid = '${threadNum}'
                         ORDER BY post.rank
                         LIMIT $start, $inc;");
    $ret = $posts->fetchAll( PDO::FETCH_ASSOC );
    $posts = NULL;
    return $ret;
  } catch ( PDOException $e ) {
    print "ERROR: " . $e->getMessage() . "<br />";

    die();
  }
}
// int -> int -> obj
function getPost($threadNum, $postRank) {
  if( !hasPerm('view.post') ) 
    return -1;

  try {
    $db = openDbConn();
    // XXX don't like this, leaves hanging PDOStatement Object
    return $db->query("SELECT post.title, post.datum, post.id, post.tid, post.rank, post.date, user.name AS uname, user.id AS uid, post.smurfKey
                         FROM post
                           LEFT JOIN user
                             ON post.uid = user.id
                           WHERE post.tid = $threadNum 
                             AND post.rank = $postRank;")->fetch();
  } catch ( PDOException $e ) {
    print "ERROR: " . $e->getMessage() . "<br />";
    die();
  }
}
?>
